const bcrypt = require('bcryptjs')
const db = require('../db/index')
const jwt = require('jsonwebtoken')
const config = require('../schema/config')
exports.reguser = (req, res) => {
  const userinfo = req.body;
  const sql = 'INSERT INTO user (username, password, security_question, security_answer) VALUES (?, ?, ?, ?)';
  userinfo.password = bcrypt.hashSync(userinfo.password, 10);
  db.query(sql, [userinfo.username, userinfo.password, userinfo.securityQuestion, userinfo.securityAnswer], (err, results) => {
    if (err) {
      return res.send({
        status: 1,
        message: [err.message, userinfo.username, userinfo.password, userinfo.securityQuestion, userinfo.securityAnswer]
      });
    }
    if (results.length > 0) {
      return res.cc('用户名已经被占用')
    }
    if (results.affectedRows !== 1) {
      return res.cc('注册用户失败')
    }
    res.send({
      status: 0,
      message: '注册成功'
    })
  });
}

exports.login = (req, res) => {
  const userinfo = req.body
  const sql = 'select * from user where username=?'
  db.query(sql, userinfo.username, (err, results) => {
    if (err) return res.cc(err)
    if (results.length !== 1)
      return res.cc('登入失败')

    const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
    if (!compareResult) return res.cc('登入失败')

    const user = { ...results[0], password: '', user_pic: '' }
    const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: '10h' })
    // console.log(tokenStr);
    res.send({
      status: 0,
      message: '登入成功',
      token: 'Bearer ' + tokenStr
    })

  }


  )
}
